import Vue from 'vue'
import VueRouter from 'vue-router'
import {userMenu} from "@/api/user";
import {listToTree} from "@/utils/treeUtil";
import store from "@/store";


Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login/Login.vue')
    },
    {
        path: '/index',
        name: 'index',
        redirect: '/index/home',
        component: () => import('@/views/layout/Index.vue'),
        children: []
    }

]

const router = new VueRouter({
    routes
})


//  路由守卫
router.beforeEach(async (to, from, next) => {
    let path = to.path;
    let token = sessionStorage.getItem("token");

    // 用户没有登录  不能访问 /index
    if (!token && path != '/login') {
        next("/login")
    }
    // 已经登录不能重复登录
    if (token && path == '/login') {
        next("/index/home")
    }

    if (token) {
        // 发送异步请求  获取用户菜单列表   存储数据vuex
        if (store.state.userMenu.length == 0) {
            let {code, data: {DBPermissions}} = await userMenu()
            if (code == 0) {
                let treeMenu = listToTree(DBPermissions)
                let lastMenu = [
                    {
                        path: 'home',
                        title: '首页',
                        icon: 'el-icon-s-home'
                    },
                    ...treeMenu
                ]
                // 将用户的权限菜单存入 vuex  后续在navView中进行使用
                store.commit("initMenu", lastMenu)

                //  根据菜单 动态生成路由
                 let DBRouter =   DBPermissions.filter(permission=>permission.isMenu==1)
                    .map(permission=>{
                        return{
                            path: permission.path,
                            component: () => import('@/views/'+permission.model+'/'+permission.component)
                        }
                    })

                let lastRouter = [
                    {
                        path: 'home',
                        name: 'home',
                        component: () => import('@/views/home/HomeView.vue')
                    },
                    ...DBRouter,
                    {
                        path: '/**',
                        name: 'page404',
                        component: () => import('@/views/page404/Page404.vue')
                    }

                ]
                console.log(JSON.stringify(lastRouter))
                // 添加路由  到index路由下
                lastRouter.forEach(rter=>{
                    router.addRoute("index",rter)
                })

                next(to.path)
            }
        }
    }
    next()
})
export default router
